package org.vt.ece4564.pcw.textinclass;

import java.util.Timer;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class MessengerService extends Service {
	
	private Cookie cookie_;
	private Timer timer_;
	private SMSReceiver receiver_;	

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startid) {
		
		String name = intent.getStringExtra("cookieName");
		String value = intent.getStringExtra("cookieValue");
		int refreshRate = intent.getIntExtra("refreshRate", -1);
		
		cookie_ = new BasicClientCookie(name, value);
		
		IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
		receiver_ = new SMSReceiver(cookie_);
		registerReceiver(receiver_, intentFilter);
		
		DownloadMessagesTask task = new DownloadMessagesTask(this, cookie_);
		timer_ = new Timer("textInClassTimer");
		timer_.scheduleAtFixedRate(task, 0, 1000*refreshRate);
		
		Log.d("CatchMessagesService", "Started");
		
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		timer_.cancel();
		unregisterReceiver(receiver_);
		
		Log.d("CatchMessagesService", "Stopped");
	}
}
